package com.feicheng.common.config;

import com.alibaba.fastjson.JSONObject;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.common.token.Token;
import com.feicheng.common.token.TokenContainer;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class ShopAdminInterceptor implements HandlerInterceptor {
	
	@Autowired
	protected TokenContainer tokenContainer;
	
    private void authFailOutput(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(ResultInfo.loginFail().toJSONString());
        out.flush();
    }

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response, Object handler)
            throws Exception {
        log.info("门店端开始鉴权："+request.getRequestURI());

        Token token = tokenContainer.getToken(TokenContainer.getCurrentTokenId());
        if (null == token) {
            authFailOutput(response);
            log.warn("门店端登录鉴权失败："+request.getRequestURI());
            return false;
        } else {
        	JSONObject tokenObject = token.getToken();
        	
        	if (null == tokenObject) {
        		authFailOutput(response);
                log.warn("门店端登录鉴权失败："+request.getRequestURI());
                return false;
        	} else {
        		JSONObject currentUserInfo = token.getToken().getJSONObject(Constant.RESULT.CURRENT);
        		
        		if (null == currentUserInfo) {
        			authFailOutput(response);
                    log.warn("门店端登录鉴权失败："+request.getRequestURI());
                    return false;
        		}
        	}
        }

        return true;
    }
}
